package com.ms.zuul.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.cloud.netflix.ribbon.RibbonHttpResponse;

import com.monitor.log.biz.core.BizLogData;
import com.monitor.log.biz.core.BizLogUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

public class AccessPostFilter extends ZuulFilter {

	@Override
	public String filterType() {
		//pre、post和error。分别代表前置过滤，后置过滤和异常过滤
		return "post";
	}
	@Override
	public int filterOrder() {
		//过滤器顺序
		return 1;
	}
	@Override
	public boolean shouldFilter() {
		//代表这个过滤器是否生效
		return true;
	}
	@Override
	public Object run() {
		if (BizLogData.getZuulReqTime() == null) {
			return null;
		}
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();

		// 记录Zuul的响应结果
		String responseResult = null;
		try {
			InputStream stream = ctx.getResponseDataStream();
			if (stream != null) {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len;
				while ((len = stream.read(buffer)) > -1 ) {
					baos.write(buffer, 0, len);
				}
				baos.flush();
				stream = new ByteArrayInputStream(baos.toByteArray());
				InputStream responseDataStream = new ByteArrayInputStream(baos.toByteArray());
				responseResult = new BufferedReader(new InputStreamReader(stream)).lines().collect(Collectors.joining(System.lineSeparator()));
				ctx.setResponseDataStream(responseDataStream);
				//ctx.setResponseBody(responseResult);
			} else {
				Object zuulResponse = RequestContext.getCurrentContext().get("zuulResponse");
				if (zuulResponse != null) {
					RibbonHttpResponse resp = (RibbonHttpResponse) zuulResponse;
					stream = resp.getBody();
					if (stream != null) {
						ByteArrayOutputStream baos = new ByteArrayOutputStream();
						byte[] buffer = new byte[1024];
						int len;
						while ((len = stream.read(buffer)) > -1 ) {
							baos.write(buffer, 0, len);
						}
						baos.flush();
						stream = new ByteArrayInputStream(baos.toByteArray());
						InputStream responseDataStream = new ByteArrayInputStream(baos.toByteArray());
						responseResult = new BufferedReader(new InputStreamReader(stream)).lines().collect(Collectors.joining(System.lineSeparator()));
						ctx.setResponseDataStream(responseDataStream);
						resp.close();
					}
				}
			}
		} catch (IOException e) {
		}
		BizLogUtil.saveLogZuulFilter(request, responseResult);
		//这里return的值没有意义，zuul框架没有使用该返回值
		return null;
	}
}